package com.myCompany.edu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.myCompany.edu.realtime.app.BaseAppV1;
import com.myCompany.edu.realtime.bean.UserUserLoginBean;
import com.myCompany.edu.realtime.common.Constant;
import com.myCompany.edu.realtime.util.AtguiguUtil;
import com.myCompany.edu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @ClassName：Dws04_DwsUserUserLogin
 * @Author: xxx
 * @Date: 2022/10/21 18:53
 * @Description:
 */
public class Dws04_DwsUserUserLogin extends BaseAppV1 {

    public static void main(String[] args) {
        new Dws04_DwsUserUserLogin().init(
             3006,
                2,
            "Dws04_DwsUserUserLogin",
                Constant.TOPIC_DWD_TRAFFIC_PAGE
        );
    }

    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {

        SingleOutputStreamOperator<JSONObject> loginPage = findLoginPage(stream);
//        loginPage.print();
        SingleOutputStreamOperator<UserUserLoginBean> beanStream = parseToPojo(loginPage);

        SingleOutputStreamOperator<UserUserLoginBean> resultStream = windowAndAgg(beanStream);

        writeToClickHouse(resultStream);
    }

    private void writeToClickHouse(SingleOutputStreamOperator<UserUserLoginBean> resultStream) {
        resultStream.addSink(FlinkSinkUtil.getClickHouseSink("dws_user_user_login_window", UserUserLoginBean.class));
    }

    private SingleOutputStreamOperator<UserUserLoginBean> windowAndAgg(SingleOutputStreamOperator<UserUserLoginBean> beanStream) {
        return beanStream
            .assignTimestampsAndWatermarks(WatermarkStrategy
                    .<UserUserLoginBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((b,ts) -> b.getTs()))
            .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(new ReduceFunction<UserUserLoginBean>() {
                        @Override
                        public UserUserLoginBean reduce(UserUserLoginBean b1, UserUserLoginBean b2) throws Exception {
                            b1.setUuCt(b2.getUuCt() + b1.getUuCt());
                            b1.setBackCt(b2.getBackCt() + b1.getBackCt());
                            return b1;
                        }
                    },
                    new ProcessAllWindowFunction<UserUserLoginBean, UserUserLoginBean, TimeWindow>() {
                        @Override
                        public void process(Context ctx, Iterable<UserUserLoginBean> elements, Collector<UserUserLoginBean> out) throws Exception {
                            UserUserLoginBean bean = elements.iterator().next();

                            bean.setStt(AtguiguUtil.toDateTime(ctx.window().getStart()));
                            bean.setEdt(AtguiguUtil.toDateTime(ctx.window().getEnd()));

                            bean.setTs(System.currentTimeMillis());

                            out.collect(bean);
                        }
                    });
    }

    private SingleOutputStreamOperator<UserUserLoginBean> parseToPojo(SingleOutputStreamOperator<JSONObject> loginPage) {
        return loginPage
            .keyBy(obj -> JSON.parseObject(obj.getString("common")).getString("uid"))
            .process(new KeyedProcessFunction<String, JSONObject, UserUserLoginBean>() {


                private ValueState<String> lastLoginDateState;

                @Override
                public void open(Configuration parameters) throws Exception {
                    lastLoginDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("lastLoginDateState", String.class));

                }

                @Override
                public void processElement(JSONObject value,
                                           Context ctx,
                                           Collector<UserUserLoginBean> out) throws Exception {
                    String lastLoginDate = lastLoginDateState.value();
                    Long ts = value.getLong("ts");
                    String today = AtguiguUtil.toDate(ts);

//                    System.out.println(ts);
//                    System.out.println(today);
//                    System.out.println(JSON.parseObject(value.getString("common")).getString("uid"));

                    Long uuCt = 0L;
                    Long backCt = 0L;

                    if (!today.equals(lastLoginDate)) {
                        uuCt =  1L;
                        lastLoginDateState.update(today);
                        if (lastLoginDate != null) {
                            long sub = (ts - AtguiguUtil.dateTimeToTs(lastLoginDate)) / 1000 / 60 / 60 / 24;
                            if(sub > 7){
                                backCt = 1L;
                            }
                        }
                    }
//                    System.out.println(uuCt);
                        out.collect(new UserUserLoginBean("","",backCt,uuCt,ts));

                }
            });
    }

    private SingleOutputStreamOperator<JSONObject> findLoginPage(DataStreamSource<String> stream) {
        return stream
            .map(JSON::parseObject)
                .filter(o -> {
                    JSONObject page = o.getJSONObject("page");
                    return page != null;
                })
            .filter(o -> {
                String uid = o.getJSONObject("common").getString("uid");
                String lastPageId = o.getJSONObject("page").getString("last_page_id");
                return (lastPageId == null || "login".equals(lastPageId)) && uid != null;
            });
    }
}
